#include <stdio.h>
#include <WinSock2.h>
#include "sys/types.h"
#include "sys/stat.h"
#include "errno.h"
#include "fcntl.h"
#include "ws2tcpip.h"
#include "string.h"
#include "stdlib.h"
#include "unistd.h"

#pragma comment(lib, "ws2_32.lib")

#define SERVER_PORT 40003


int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0); //解决debug时，scanf优于printf捕获的问题
    //客户端只需要一个套接字文件描述符，用于和服务器通信
    struct WSAData wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        perror("WSADATA失败");
    }
    int clientSocket;
    //描述服务器的socket
    struct sockaddr_in serverAddr;
    char sendbuf[200];
    char recvbuf[200];
    int iDataNum;

    if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        return 1;
    }
    serverAddr.sin_family = AF_INET;

    serverAddr.sin_port = htons(SERVER_PORT);

//指定服务器端的ip，本地测试：127.0.0.1

//inet_addr()函数，将点分十进制IP转换成网络字节序IP

    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(clientSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {

        perror("no connect");

        return 1;
    }
    printf("连接到主机...\n");

    while (1) {

        printf("发送消息:");

        scanf("%s", sendbuf);

        printf("\n");


         //断线重连


        send(clientSocket, sendbuf, strlen(sendbuf), 0);


        if (strcmp(sendbuf, "quit") == 0)

            break;

        printf("读取消息:");

        recvbuf[0] = '\0';

        iDataNum = recv(clientSocket, recvbuf, 200, 0);

        recvbuf[iDataNum] = '\0';

        printf("%s\n", recvbuf);

    }

    close(clientSocket);

    return 0;
}
